package service

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"errors"
	"gitee.com/gopher2011/godemo/logger"
	"gitee.com/gopher2011/godemo/server/dao"
	"math/rand"
)

// 全局公开对象
var User = userService{}


// 用户信息表
// 私有对象，所有的方法都绑定到这个结构体上。
type userService struct{}

func (p *userService) CreateUser(arg dao.User) (errMsg string, err error) {
	var user dao.UserLogin
	sql1 :=`select * from user_login where email = ?`
	dao.DB.Get(&user,sql1, arg.Email)
	if user.Uid >0 {
		errMsg = "该邮箱已注册过"
		err = errors.New(errMsg)
		return
	}

	sql2 := `select * from user_login where username = ?`
	dao.DB.Get(&user,sql2,arg.Username)
	if user.Uid >0 {
		errMsg = "用户名已存在"
		err = errors.New(errMsg)
		return
	}

	p.doCreate(arg)


	return 0, nil
}

func Md5 (str []byte)string{
	h := md5.New()
	h.Write(str)
	return hex.EncodeToString(h.Sum(nil))
}

func (p *userService) doCreate(arg dao.User,password string) (int64, error) {
	if arg.Avatar == "" && len(DefaultAvatars)>0 {
		// 随机生成一个默认头像
		arg.Avatar = DefaultAvatars[rand.Intn(len(DefaultAvatars))]
	}
	arg.Open = 0
	arg.IsAuth = dao.DefaultAuth
	// 存用户登基本信息
	s1:= dao.UserDao.Tx()
	s1.Begin(nil)
	res, err := dao.UserDao.InsertTemplate(arg, s1)
	if err != nil {
		return res, err
	}
	userLogin := dao.UserLogin{
		Email: arg.Email,
		Username: arg.Username,
		Uid: arg.Uid,
		Passwd:Md5([]byte(password)),
	}
	// 存用户登录信息
	s2 := dao.UserLoginDao.Tx()
	s2.Begin(nil)
	res2, err := dao.UserLoginDao.InsertTemplate(userLogin, s2)
	if err != nil {
		return res2, err
	}

	//存用户角色信息
	if !arg.IsRoot {
		userRole :=
	}





	return 0, nil
}

func (p *userService) Delete() (int64, error) {
	return 0, nil
}

func (p *userService) Update(arg dao.User) (int64, error) {
	return 0, nil
}

func (p *userService) Select(id int64) (dao.User, error) {
	return dao.UserDao.SelectTemplate(id)
}

// 原 UserRichLogic
func (p *userService)Total(uid int)int64{
	total, err := dao.UserDao.Total(uid)
	if err != nil {
		logger.Errorln("UserRichLogic Total error:",err)
	}
	return total
}


